package net.topikachu.dynamic.faces;

import java.io.IOException;
import java.util.Map;

import javax.el.ValueExpression;
import javax.el.VariableMapper;
import javax.faces.component.UIComponent;

import net.topikachu.dynamic.screen.widget.FaceletWidget;

import com.sun.facelets.FaceletContext;
import com.sun.facelets.el.VariableMapperWrapper;

public class WidgetExecutor {
	static public void executeWidget(FaceletContext ctx, UIComponent parent,
			FaceletWidget faceletWidget) throws IOException {
		VariableMapper orig = ctx.getVariableMapper();

		// setup a variable map

		Map<String, String> variables = faceletWidget.getVariables();
		if (variables != null && variables.size() > 0) {
			VariableMapper varMapper = new VariableMapperWrapper(orig);
			for (Map.Entry<String, String> entry : variables.entrySet()) {
				varMapper.setVariable(entry.getKey(), createValueExpression(
						ctx, entry.getValue()));
			}

			ctx.setVariableMapper(varMapper);
		}
		try {
			ctx.includeFacelet(parent, faceletWidget.getFacelet());
		} finally {
			ctx.setVariableMapper(orig);
		}

	}

	static private ValueExpression createValueExpression(FaceletContext ctx,
			String value) {
		ValueExpression entityExpression = ctx.getExpressionFactory()
				.createValueExpression(ctx, value, Object.class);
		return entityExpression;
	}
}
